/*
 * @Copyright: Copyright (c) 2030 吴周海
 * @Author: wzh200x@126.com
 * @Date: 2025-10-10 11:35:00
 * @LastEditors: wzh200x@126.com
 * @LastEditTime: 2025-10-15 16:48:42
 * @FilePath: \gogamewebserver\goGameWebServer\internal\model\entity\cdKeyModel.go
 * @Description: CdKey 实体模型
 */
package entity

import (
	"goGameWebServer/internal/common/logger"
	"goGameWebServer/internal/common/utils"
	"goGameWebServer/internal/defines/cerror"
	"goGameWebServer/internal/defines/dataType"
	"goGameWebServer/internal/interfaces"
	"goGameWebServer/internal/manager/databasemanager"

	"github.com/gogf/gf/v2/errors/gcode"
	"github.com/gogf/gf/v2/errors/gerror"
	"github.com/gogf/gf/v2/util/gmeta"
)

type CdKeyModelData struct {
	gmeta.Meta  `orm:"table: cd_key"`
	Id          dataType.TypeDataBaseId `orm:"id"`          // ID
	GroupId     dataType.TypeDataBaseId `orm:"groupId"`     // 组ID
	Code        string                  `orm:"code"`        // key
	CreateTime  string                  `orm:"createTime"`  // 创建时间
	LimitTime   string                  `orm:"limitTime"`   // 限制时间
	CanUseCount int                     `orm:"canUseCount"` // 使用次数
	UsedCount   int                     `orm:"usedCount"`   // 已使用次数
}

func (d *CdKeyModelData) Reset() {
	d.Id = 0
	d.GroupId = 0
	d.Code = ""
	d.CreateTime = ""
	d.LimitTime = ""
	d.CanUseCount = 0
	d.UsedCount = 0
}

type CdKeyModel struct {
	EntityModel
}

func (m *CdKeyModel) LoadEntityDataFromDB(records interface{}) error {
	base, err := databasemanager.ManagerDatabase().DefaultDataBase()
	if err != nil {
		return err
	}
	if entityData, ok := m.EntityData.(*CdKeyModelData); ok {
		db := base.GetDb().Model(m.Template)
		if entityData.Id != 0 {
			one, err := db.Where("id", entityData.Id).One()
			if err != nil {
				return err
			}
			if one == nil {
				return m.Create()
			}
			_ = one.Struct(m.EntityData)
			m.SetEntityDBID(entityData.Id)
			return nil
		}
		if entityData.Code != "" {
			one, err := db.Where("code", entityData.Code).One()
			if err != nil {
				return err
			}
			if one == nil {
				return m.Create()
			}
			_ = one.Struct(m.EntityData)
			m.SetEntityDBID(entityData.Id)
			return nil
		}
		return gerror.NewCodef(gcode.New(cerror.ERROR_ENTITY_PROPERTY_INVALID, "", nil), "cd_key model load need id or code")
	}
	return gerror.NewCodef(gcode.New(cerror.ERROR_ENTITY_PROPERTY_INVALID, "", nil), "cd_key model data is invalid")
}

func (m *CdKeyModel) Create() error {
	if entityData, ok := m.EntityData.(*CdKeyModelData); ok {
		entityData.CreateTime = utils.GetNowTimeFormat()
		entityData.UsedCount = 0
		err := m.CreateDataToDB()
		entityData.Id = m.EntityDBID
		if err != nil {
			return err
		}
		logger.LoggerIns().Debug("create cd_key success")
		return nil
	}
	return gerror.NewCodef(gcode.New(cerror.ERROR_ENTITY_PROPERTY_INVALID, "", nil), "cd_key model create fail, data is invalid")
}

func NewCdKeyModel(name string) interfaces.IEntityModel {
	m := &CdKeyModel{
		EntityModel: NewEntityModel(name),
	}
	m.SetEntityData(&CdKeyModelData{
		Id:          0,
		GroupId:     0,
		Code:        "",
		CreateTime:  "",
		LimitTime:   "",
		CanUseCount: 0,
		UsedCount:   0,
	})
	m.SetTemplate(m.EntityData)
	return m
}

func CodeIsExist(code string) bool {
	base, err := databasemanager.ManagerDatabase().DefaultDataBase()
	if err != nil {
		return false
	}
	re, e := base.GetDb().Model(&CdKeyModelData{}).Where("code", code).One()
	if e != nil {
		return false
	}
	return re != nil
}

// 按照groupId,page,pageSize查询
func CdkeyQueryByGroupId(groupId, page, pageSize int) ([]*CdKeyModelData, error) {
	base, err := databasemanager.ManagerDatabase().DefaultDataBase()
	if err != nil {
		return nil, err
	}
	var list []*CdKeyModelData
	corders, err := base.GetDb().Model(&CdKeyModelData{}).Where("groupId", groupId).Limit(pageSize).Offset((page - 1) * pageSize).All()
	if err != nil {
		return nil, err
	}
	corders.Structs(&list)
	return list, nil
}
